const express = require('express')
const router = express.Router()

const path = require('path')

const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')
const adapters = new FileSync(path.resolve(__dirname, '../data/db.json'))
const db = low(adapters)

const shortid = require('shortid')

const AccountModule = require('../modules/AccountModule')


/* 记账本首页页面 */
router.get('/', function(req, res, next) {
  AccountModule.find().sort({ tiem: -1 }).then(data => {
    const accounts = data
    res.render('index', { accounts })
  }).catch(error => {
    console.log('账单查询失败', error)
  })
})

/* 记账本添加页面 */
router.get('/add', (req, res, next) => {
  res.render('add')
})

/* 账单添加 */
router.post('/add', (req, res, next) => {
  AccountModule.insertOne(req.body).then(() => {
    res.render('result', { message: '添加成功！' })
  }).catch(error => {
    console.log('账单添加失败', error)
  })
})

/* 账单删除 */
router.get('/delete/:id', (req, res, next) => {
  AccountModule.deleteOne({ _id: req.params.id }).then(data => {
    res.render('result', { message: '删除成功！' })
  }).catch(error => {
    console.log('账单删除失败', error)
  })
})

module.exports = router
